<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Goods;
use App\Models\GoodsNexus;
use App\Models\RfidWarehouse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Excel;
use Illuminate\Validation\Validator;

class RfidmanageController extends Controller {
	/*
	 * @rfid管理的列表页面与搜索分页页面
	*/
	public function index(Request $request) {
		if ($request->isMethod('post')) {
			$rfid = $request->input('rfid');
			$paginate = 15;
			$rfid_lists = Goods::join('goods_nexus', 'goods_nexus.goods_id', '=', 'goods.id')
				->select('goods_nexus.*', 'goods.product_code')
				->where('rfid', 'like', '%' . $rfid . '%')
				->paginate($paginate);
//            统计页数
			$count = Goods::join('goods_nexus', 'goods_nexus.goods_id', '=', 'goods.id')
				->select('goods_nexus.*', 'goods.product_code')
				->where('rfid', 'like', '%' . $rfid . '%')->count(); //总数
			$total_page = ceil($count / $paginate); //共多少页
			//带到视图的参数有:分页带的参数,数据库查询的数据,总页数的统计
			return view('admin.rfidmanage', ['rfid' => $rfid])
				->with('rfid_lists', $rfid_lists)
				->with('total_page', $total_page);
		}
		/*=======get的传递方式==========*/
//           //注意参数post请求表单的username,  get请求post的name
		$rfid = $request->input('rfid');
		$paginate = 15;
		$rfid_lists = Goods::join('goods_nexus', 'goods_nexus.goods_id', '=', 'goods.id')
			->select('goods_nexus.*', 'goods.product_code')
			->where('rfid', 'like', '%' . $rfid . '%')
			->paginate($paginate);
//        统计页数
		$count = Goods::join('goods_nexus', 'goods_nexus.goods_id', '=', 'goods.id')
			->select('goods_nexus.*', 'goods.product_code')
			->where('rfid', 'like', '%' . $rfid . '%')->count(); //总数
		$total_page = ceil($count / $paginate); //共多少页
		//带到视图的参数有:分页带的参数,数据库查询的数据,总页数的统计
		return view('admin.rfidmanage', ['rfid' => $rfid])
			->with('rfid_lists', $rfid_lists)
			->with('total_page', $total_page);
	}
	/*
	 * @RFID码仓库的页面
	 */
	public function warehouse(){
	    $paginate=15;//每页的分页数
	    $warehouses=RfidWarehouse::leftJoin('goods','goods.id','=','rfid_warehouse.product_id')
            ->select('rfid_warehouse.*')
            ->paginate($paginate);

	    $count=DB::table('rfid_warehouse')->count();//总数
        $total_page = ceil($count / $paginate); //共多少页
       return view('admin.rfid_warehouse')
             ->with('warehouses',$warehouses)
             ->with('total_page', $total_page);
    }
    /*
     * *********@@@RFID码仓库的导入模板*************
     * 现在要下载的文件保存在public/leading
     * 以前的public\goods.xlsx是商品管理的导入
     * 以前的public\rfid.xlsx是商品管理中的商品详情的RFID列表的导入
     */
    public function housedownload(){
        return response()
            ->download(realpath(base_path('public/leading')) . '/rfid_house.xlsx', "rfid码仓库导入表" . '.xlsx');
    }
    /*
     * @模板是public/leading/rfid_house.xlsx
     * @RFID码仓库的导入
     */
    public function houseimport(Request $request){
        //laravel excel的两种写法之一,注意作用域链
        $data = Excel::load($request->file('excel'), function($reader) {})->get()->toArray();
        //exce1表格中$ch_arr商品序号不能为空
        $sh_array = array();
        foreach ($data[0] as $ite){
            reset($ite);
            $first=current($ite);
            array_push($sh_array,$first);
        }
        //循环遍历第一项是否为空
        foreach($sh_array as $v) {
            if (empty($v)) {
                return response()->json(['status' => 0, 'msg' => '商品序号不能为空']);
            }
        }
        $xh_array = array();
        foreach ($data[0] as $itee){
            reset($itee);
            current($itee);
            $secnd=next($itee);
            array_push($xh_array, $secnd);
        }
//        dd($xh_array);
        foreach($xh_array as $v) {
            if (empty($v)) {
                return response()->json(['status' => 0, 'msg' => 'rfid不能为空']);
            }
        }
        $ch_array = array();
        foreach ($data[0] as $item){
            reset($item);
            current($item);
            $first=next($item);
            array_push($ch_array,$first);
        }
       //判断导入的数据是非有重复值
        if (count($ch_array) != count(array_unique($ch_array))) {
            return response()->json(['status'=>0,'msg'=>'该导入数组有重复值']);
        }
//        dd($ch_array);
        //导入的数据与数据库的数据是否重复
        $warehouses= RfidWarehouse::where('rfid','=',$ch_array[0])->first();
        if($warehouses){
            return response()->json(['status'=>0,'msg'=>'导入失败,rfid码重复']);
        }
        foreach ($data as $value) {//循环sheet
            if(!empty($value)){
                $titleArr = array_keys($value[0]);
                //判断表头的数据是非正确,防止其他文件的导入
                if($titleArr[0] != '商品序号'){
                    return response()->json(['status'=>0,'msg'=>'导入失败']);
                }

                if($titleArr[1] != 'rfid码'){
                    return response()->json(['status'=>0,'msg'=>'导入失败']);
                }
            }
            //数据通过models传到数据库中
            foreach($value as $rfidData){
                RfidWarehouse::create([
                        'product_id'=>$rfidData['商品序号'],
                        'rfid'=>$rfidData['rfid码']
                ]);
            }
        }
        return ['status'=>1,'msg'=>'导入成功'];
    }
    /*
     * @Rfid管理的列表的模板下载
     */
    public function download(){
        return response()
            ->download(realpath(base_path('public/leading')) . '/rfid_now.xlsx', "rfid码在线导入表" . '.xlsx');
    }
    /*
     * @Rfid管理的列表的导入
     */
    public function  import(Request $request){
        //laravel excel的两种写法之一,注意作用域链
        $data = Excel::load($request->file('excel'), function($reader) {})->get()->toArray();
        //exce1表格中$ch_arr商品序号不能为空
        $sh_array = array();
        foreach ($data[0] as $ite){
            reset($ite);
            $first=current($ite);
            array_push($sh_array,$first);
        }
        //循环遍历第一项是否为空
        foreach($sh_array as $v) {
            if (empty($v)) {
                return response()->json(['status' => 0, 'msg' => '导入格式不正确']);
            }
        }
        $xh_array = array();
        foreach ($data[0] as $itex){
            reset($itex);
            current($itex);
            $second=next($itex);
            array_push($xh_array,$second);
        }
        //循环遍历第二项是否为空
        foreach($xh_array as $v) {
            if (empty($v)) {
                return response()->json(['status' => 0, 'msg' => 'rfid不能为空']);
            }
        }
        //exce1表格中是非有重复值
        $ch_array = array();
          foreach ($data[0] as $item){
           array_push($ch_array,end($item));
        }

        //exce1表格中判断导入的数据是非有重复值
        if (count($ch_array) != count(array_unique($ch_array))) {
            return response()->json(['status'=>0,'msg'=>'该excel导入有重复值']);
        }
        //导入的数据与数据库的数据是否重复
//        dd($ch_array[0]);
        $charray=$ch_array[0];
//        dd($charray);
        $warehouses= GoodsNexus::where('rfid','=', $charray)->first();
        if($warehouses){
            return response()->json(['status'=>0,'msg'=>'导入失败,rfid码重复或者提交表单不正确']);
        }

        foreach ($data as $value) {//循环sheet
            if(!empty($value)){
                $titleArr = array_keys($value[0]);
                //判断表头的数据是非正确,防止其他文件的导入
                if($titleArr[0] != '商品序号'){
                    return response()->json(['status'=>0,'msg'=>'导入失败']);
                }
                if($titleArr[1] != 'rfid码'){
                    return response()->json(['status'=>0,'msg'=>'导入失败']);
                }
            }
            //数据通过models传到数据库中
            foreach($value as $rfidData){
                GoodsNexus::create([
                    'goods_id'=>$rfidData['商品序号'],
                    'rfid'=>$rfidData['rfid码'],
                ]);
            }
        }
        return ['status'=>1,'msg'=>'导入成功'];
    }
    /*
     * @删除
     */
    public function  destroy($id){
        $rfidwares = GoodsNexus::find($id);
        if ($rfidwares->delete()) {
            return redirect('admin/rfidmanage');
        } else {
            return redirect()->back();
        }

    }
    /*
     * @rfid仓库与商品列表的关联关系
     */
    public function associated(Request $request){
        //获取指定的id
        $id = $request->id;
        $rfidhouses=RfidWarehouse::find($id);
        //rfid仓库中的rfid
        $rfidware=$rfidhouses->rfid;
        //判断rfid仓库中的rfid是否与数据库的rfid在线的rfid码是否相等
        $warehouses= GoodsNexus::where('rfid','=',$rfidware)->first();
        if($warehouses){
            return response()->json(['status'=>0,'msg'=>'关联不成功,rfid码重复']);
        }
        //导入数据
        $sql=DB::insert("insert into goods_nexus( goods_id ,rfid,created_at,updated_at) values (?,?,?,?)",
            [$rfidhouses->product_id,$rfidhouses->rfid,$rfidhouses->created_at,$rfidhouses->updated_at]);
//        成功将rfid仓库点击关联的数据删除
        if($sql){
            $rfidhouses->delete();
            return ['status'=>1,'msg'=>'关联成功'];
        }else{
            return response()->json(['status'=>0,'msg'=>'关联不成功']);
        }
//       return redirect("admin/commodity");

    }
}
